﻿using Inaction.Business.Security;
using System.Linq;
using System.Windows.Forms;

namespace Inaction.UI
{
    public partial class UserManageForm : BaseForm
    {
        #region 属性/变量
        private UserCriteria Criteria
        {
            get { return criteriaBindingSource.DataSource as UserCriteria; }
            set { criteriaBindingSource.DataSource = value; }
        }
        private UserInfo CurrentUser
        {
            get { return userInfoListBindingSource.Current as UserInfo; }
        }
        private RoleInfoList Roles
        {
            get { return roleInfoListBindingSource.List as RoleInfoList; }
        }
        #endregion

        #region 构造
        public UserManageForm()
        {
            InitializeComponent();
            Criteria = new UserCriteria { Type = Inaction.Security.UserType.User };
        }
        #endregion 构造

        #region 事件

        private void userInfoListBindingSourceChanged(object sender, System.EventArgs e)
        {
            ShowUserRoles();
        }

        private void barManager_FormRulesApplied(object sender, System.EventArgs e)
        {
            checkedListBox.Enabled = barManager.EditMode;
        }

        private void checkedListBox_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
        {
            if (CurrentUser == null || inRefresh || e.Index < 0) return;
            var role = checkedListBox.GetItem(e.Index) as RoleInfo;
            role.Selected = e.State == CheckState.Checked;
            CurrentUser.RefreshUserRole(role);
        }
        #endregion

        #region 方法
        bool inRefresh = false;
        private void ShowUserRoles()
        {
            if (Roles == null) return;
            inRefresh = true;
            if (CurrentUser == null)
            {
                checkedListBox.UnCheckAll();
                foreach (var role in Roles) role.Selected = false;
            }
            else
            {
                for (int i = 0; i < Roles.Count; i++)
                {
                    var role = Roles[i];
                    role.Selected = CurrentUser.UserRoles.Any(p => p.RoleId == role.Id);
                    checkedListBox.SetItemChecked(i, role.Selected);
                }
            }
            inRefresh = false;
        }
        #endregion  
    }
}
